package com.example.mvvmtemplate.utli;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaDrm;
import android.media.UnsupportedSchemeException;
import android.text.TextUtils;

import com.example.mvvmtemplate.utli.log.PrintLog;

import java.util.UUID;

public class IdUtil {

    /**
     * 获取设备唯一id
     */
    public static String getID(Context context) {
        SharedPreferences sharedPreferences = SharedPreferencesUtil.getInstance().getSharedPreferences(context);
        String uuid = sharedPreferences.getString("uuid", "");
        if (TextUtils.isEmpty(uuid)) {
            uuid = getUUID();
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString("uuid", uuid);
            edit.apply();
        }
        PrintLog.printError("UUID", uuid);
        return uuid;
    }

    private static String getUUID() {
        UUID wideVineUuid = new UUID(-0x121074568629b532L, -0x5c37d8232ae2de13L);
        try {
            MediaDrm wvDrm = new MediaDrm(wideVineUuid);
            byte[] wideVineId = wvDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID);
            StringBuilder stringBuilder = new StringBuilder();
            for (byte b : wideVineId) {
                stringBuilder.append(b);
            }
            return stringBuilder.toString();
        } catch (UnsupportedSchemeException e) {
            e.printStackTrace();
        }
        return UUID.randomUUID().toString();
    }

}
